package utils

import (
	"fmt"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"github.com/satori/go.uuid"
	"talent.com/agency_im/conf"
	"talent.com/server/durotar.git/tools/tz"
	"time"
)


type ImageUploadToken struct {
	Key   string
	Token string
}

func GetImageUploadToken() *ImageUploadToken {
	mac := qbox.NewMac(conf.ServerConfig().Qiniu.AccessKey, conf.ServerConfig().Qiniu.SecretKey)
	keyToOverwrite := genImageKey()
	putPolicy := storage.PutPolicy{
		Scope: fmt.Sprintf("%s:%s", conf.ServerConfig().Qiniu.ImageBucket, keyToOverwrite),
		Expires: uint32(tz.GetNowTs()) + 3600,
		FsizeLimit: 10 * 1024 * 1024, // 10M
		MimeLimit: "image/*", // 只限制上传图片
	}
	fmt.Printf("bucket: %v, key: %v \n", conf.ServerConfig().Qiniu.ImageBucket, keyToOverwrite)
	upToken := putPolicy.UploadToken(mac)
	return &ImageUploadToken{keyToOverwrite, upToken}
}

func GetImageDownloadURL(key string) string {
	mac := qbox.NewMac(conf.ServerConfig().Qiniu.AccessKey, conf.ServerConfig().Qiniu.SecretKey)
	deadline := tz.GetNowTs() + 3600 * 24 * 7 //1天有效期
	privateAccessURL := storage.MakePrivateURL(mac, conf.ServerConfig().Qiniu.ImageHost, key, deadline)
	return privateAccessURL
}

func genImageKey() string {
	return fmt.Sprintf("%v/%v", time.Now().Format("2006/01/02"), uuid.NewV1())
}
